﻿// This script handles detecting collisions with traps and telling the Game Manager
// when the player dies

using UnityEngine;

public class PlayerHealth : MonoBehaviour
{
    public GameObject deathVFXPrefab; //The visual effects for player death
    public PlayerCheckpoint pCheckPoint;
    public GameObject deathTip;


    public bool isAlive = true; //Stores the player's "alive" state
    int trapsLayer; //The layer the traps are on

    private PlayerMovement _playerMovement;

    private void Start()
    {
        //Get the integer representation of the "Traps" layer
        trapsLayer = LayerMask.NameToLayer("Traps");

        _playerMovement = GetComponent<PlayerMovement>();
        if (deathTip == null)
        {
            Debug.LogError("需要给主角加上死亡后提示。Prefab在:Assets/Props/DeathTip.prefab");
            return;
        }
        deathTip.SetActive(false);
    }

    void Update()
    {
        if (!isAlive && Input.GetKeyDown(KeyCode.X))
        {
            PlayerRecover();
        }
    }

    void OnTriggerEnter2D(Collider2D collision)
    {
        //If the collided object isn't on the Traps layer OR if the player isn't currently
        //alive, exit. This is more efficient than string comparisons using Tags
        if (collision.gameObject.layer != trapsLayer || !isAlive)
            return;

        //Trap was hit, so set the player's alive state to false

        //Instantiate the death particle effects prefab at player's location
        //Instantiate(deathVFXPrefab, transform.position, transform.rotation);

        //Tell the Game Manager that the player died and tell the Audio Manager to play
        //the death audio
        PlayerDied();
        //GameManager.PlayerDied();

        AudioManager.PlayDeathAudio();
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        //If the collided object isn't on the Traps layer OR if the player isn't currently
        //alive, exit. This is more efficient than string comparisons using Tags
        if (collision.gameObject.layer != trapsLayer || !isAlive)
            return;

        //Trap was hit, so set the player's alive state to false

        //Instantiate the death particle effects prefab at player's location
        //Instantiate(deathVFXPrefab, transform.position, transform.rotation);

        //Tell the Game Manager that the player died and tell the Audio Manager to play
        //the death audio
        PlayerDied();
        //GameManager.PlayerDied();

        AudioManager.PlayDeathAudio();
    }

    void PlayerDied()
    {
        isAlive = false;
        
        //Disable player game object
        _playerMovement.BlockInput();

        Debug.Log("玩家死亡");

        deathTip.SetActive(true);
    }

    void PlayerRecover()
    {
        pCheckPoint.ReturnToCheckpoint();
        isAlive = true;

        deathTip.SetActive(false);

        _playerMovement.UnblockInput();
    }
}